import { MemoryStorage, WebStorage } from './storage'

const _global = (typeof window !== 'undefined' ? window : global || {})

export default class CreateLs extends WebStorage {
  install

  constructor(opt) {
    const _options = {
      ...opt,
      storage: opt.storage || 'local',
      name: opt.name || 'ls'
    }

    if (_options.storage && ['memory', 'local', 'session'].indexOf(_options.storage) === -1) {
      throw new Error(`Vue-ls: Storage "${_options.storage}" is not supported`)
    }
    let store = null

    switch (_options.storage) {
      case 'local':
        store = 'localStorage' in _global
          ? _global.localStorage
          : null

        break

      case 'session':
        store = 'sessionStorage' in _global
          ? _global.sessionStorage
          : null

        break
      case 'memory':
        store = MemoryStorage
        break
    }
    super(store)

    this.setOptions(Object.assign(this.options, {
      namespace: ''
    }, _options || {}))

    Object.defineProperty(this, 'install', {
      get: () => {
        return (app) => {
          Object.defineProperty(app.config.globalProperties, `$${_options.name}`, {
            enumerable: true,
            get: () => this
          })
        }
      }
    })
  }
}
